﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CommonTagTime.Business;
using CommonTagTime.ModelObject;
using CommonTagTime;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Drawing;
using System.Drawing.Imaging;
using System.Data;
public partial class admin_ProductDetail : SitePage
{
    #region Fields
    public string html = string.Empty;
    private ProductCategoryCollection lstCate = new ProductCategoryCollection();
    public string ImageProduct1
    {

        get
        {
            object o = ViewState["ImageProduct1"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ImageProduct1"] = value; }

    }
    public string ImageProduct2
    {

        get
        {
            object o = ViewState["ImageProduct2"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ImageProduct2"] = value; }

    }
    public string ImageProduct3
    {

        get
        {
            object o = ViewState["ImageProduct3"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ImageProduct3"] = value; }

    }
    public string ImageProduct4
    {

        get
        {
            object o = ViewState["ImageProduct4"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["ImageProduct4"] = value; }

    }
    public string Command
    {

        get
        {
            object o = ViewState["Command"];
            if (o != null) return (string)o;
            return string.Empty;
        }

        set { ViewState["Command"] = value; }

    }
    public int ProductID
    {

        get
        {
            object o = ViewState["ProductID"];
            if (o != null) return (int)o;
            return int.MinValue;
        }

        set { ViewState["ProductID"] = value; }

    }
    public int ImageProductID2
    {

        get
        {
            object o = ViewState["ImageProductID2"];
            if (o != null) return (int)o;
            return int.MinValue;
        }

        set { ViewState["ImageProductID2"] = value; }

    }
    public int ImageProductID3
    {

        get
        {
            object o = ViewState["ImageProductID3"];
            if (o != null) return (int)o;
            return int.MinValue;
        }

        set { ViewState["ImageProductID3"] = value; }

    }
    public int ImageProductID4
    {

        get
        {
            object o = ViewState["ImageProductID4"];
            if (o != null) return (int)o;
            return int.MinValue;
        }

        set { ViewState["ImageProductID4"] = value; }

    }
    public int ImageProductID1
    {

        get
        {
            object o = ViewState["ImageProductID1"];
            if (o != null) return (int)o;
            return int.MinValue;
        }

        set { ViewState["ImageProductID1"] = value; }

    }
    #endregion

    #region Init,Load
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadData();
            LoadDataCategory();
        }
    }
    protected override void OnInitComplete(EventArgs e)
    {
        base.OnInitComplete(e);
        InitData();
    }
    #endregion

    #region Methods
    
    private bool CategoryIsSelect(ProductCategoryCollection lstSource, Category objItemFind)
    {
        if (lstSource != null && lstSource.Count > 0)
        {
            foreach (ProductCategory objCate in lstSource)
            {
                if (objCate.CategoryID == objItemFind.CategoryID)
                    return true;

            }
            return false;
        }
        return false;
    }
    private void LoadData()
    {
        //DropDownList Zone
        busZone bus = new busZone();
        ZoneCollection list = bus.ListAll();
        if (list != null && list.Count > 0)
        {
            drpZone.Items.Add(new ListItem("Chọn...", "0"));
            foreach (Zone item in list)
            {
                drpZone.Items.Add(new ListItem(item.Name, item.ZoneId.ToString()));
            }
        }


        //DropDownList Note
        clsSQL sql = new clsSQL();
        DataTable dt = sql.ExecDataTable("SELECT Title, NoteId FROM Note");
        if (dt != null)
        {
            if (dt.Rows.Count > 0)
            {
                drpNote.DataSource = dt;
                drpNote.DataTextField = "Title";
                drpNote.DataValueField = "NoteId";
                drpNote.DataBind();

                drpNote.Items.Insert(0, new ListItem("", ""));

                dt.Dispose();
            }
        }

        //Color
        dt = sql.ExecDataTable("SELECT DISTINCT Color FROM Product ORDER BY Color ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpColor.DataSource = dt;
            drpColor.DataTextField = "Color";
            drpColor.DataValueField = "Color";
            drpColor.DataBind();

            dt.Dispose();
        }

        //Size
        dt = sql.ExecDataTable("SELECT DISTINCT Size FROM Product ORDER BY Size ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpSize.DataSource = dt;
            drpSize.DataTextField = "Size";
            drpSize.DataValueField = "Size";
            drpSize.DataBind();

            dt.Dispose();
        }

        //Material
        dt = sql.ExecDataTable("SELECT DISTINCT Material FROM Product ORDER BY Material ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpMaterial.DataSource = dt;
            drpMaterial.DataTextField = "Material";
            drpMaterial.DataValueField = "Material";
            drpMaterial.DataBind();

            dt.Dispose();
        }

        //MadeIn
        dt = sql.ExecDataTable("SELECT DISTINCT MadeIn FROM Product ORDER BY MadeIn ASC");
        if (dt != null && dt.Rows.Count > 0)
        {
            drpMadeIn.DataSource = dt;
            drpMadeIn.DataTextField = "MadeIn";
            drpMadeIn.DataValueField = "MadeIn";
            drpMadeIn.DataBind();

            dt.Dispose();
        }

        if (this.Command == "edit")
        {
            busProduct objBus = new busProduct();
            Product objProduct = objBus.GetByID(ProductID);
            if (objProduct != null)
            {//bind data to control
                txtSKU.Text = objProduct.SKU;
                txtProductName.Text = objProduct.Name;
                if (objProduct.IsActive)
                    chkIsActive.Checked = true;
                else chkIsActive.Checked = false;
                if (objProduct.IsNew)
                    chkIsNew.Checked = true;
                else chkIsNew.Checked = false;
                drpZone.SelectedValue = objProduct.ZoneId.ToString();
                drpStatus.SelectedValue = objProduct.Status.ToString();
                drpNote.SelectedValue = objProduct.NoteId.ToString();
                txtDescription.Text = objProduct.Description;
                txtNowPrice.Text = string.Format("{0:00000}", objProduct.NowPrice);
                if (objProduct.WasPrice > 0)
                    txtWasPrice.Text = string.Format("{0:00000}", objProduct.WasPrice);
                txtShortDescription.Text = objProduct.ShortDescription;
                txtPageTitle.Text = objProduct.PageTitle;
                txtMetaKeywords.Text = objProduct.MetaKeywords;
                txtMetaDescription.Text = objProduct.MetaDescription;
                txtSite.Text = objProduct.Site;
                txtVideo.Text = objProduct.Video;

                txtSize.Text = objProduct.Size;
                txtColor.Text = objProduct.Color;
                txtMaterial.Text = objProduct.Material;
                txtMadeIn.Text = objProduct.MadeIn;

                drpSize.SelectedValue = objProduct.Size;
                drpColor.SelectedValue = objProduct.Color;
                drpMaterial.SelectedValue = objProduct.Material;
                drpMadeIn.SelectedValue = objProduct.MadeIn;

                //get Video Resource
                if (objProduct.Video != string.Empty)
                {
                    ltrVideo.Text = clsVideo.GetVideoResource(objProduct.Video, 300, 200, 1, 0);
                    trVideo.Visible = true;
                }
                else trVideo.Visible = false;
                LoadProductImage(this.ProductID);
                busProductCategory objBusCate = new busProductCategory();
                lstCate = objBusCate.GetListByProductID(this.ProductID);
            }
        }
        else
        {
            clsSQL clsSQL = new clsSQL();
            string strSKU = string.Empty;
            try
            {
                strSKU = Convert.ToString((int)clsSQL.ExecuteScalar("select top 1 ProductId from Product order by ProductId DESC") + 1);
            }
            catch
            {
                strSKU = "00001";
            }
                
            txtSKU.Text = strSKU.ToString();
        }
    }
    private ImageProduct GetImageInList(ImageProductCollection lstImage, int index)
    {

        try
        {
            return lstImage[index];
        }
        catch
        {
        }
        return null;
    }
    private void LoadProductImage(int productID)
    {
        busImageProduct objBus = new busImageProduct();
        ImageProductCollection lstImage = objBus.GetListByProductID(productID);
        if (lstImage != null && lstImage.Count > 0)
        {
            ImageProduct objImage1 = GetImageInList(lstImage, 0);
            if (objImage1 != null)
            {
                this.ImageProductID1 = objImage1.ImageProductID;
                //bind image to UI
                this.ImageProduct1 = objImage1.FileName;
                BindImage(trImage1, trDelete1, imgProductImage1, lbtnDeleteImage1, this.ImageProduct1);
            }
            ImageProduct objImage2 = GetImageInList(lstImage, 1);
            if (objImage2 != null)
            {
                this.ImageProductID2 = objImage2.ImageProductID;
                //bind image to UI
                this.ImageProduct2 = objImage2.FileName;
                BindImage(trImage2, trDelete2, imgProductImage2, lbtnDeleteImage2, this.ImageProduct2);
            }
            ImageProduct objImage3 = GetImageInList(lstImage, 2);
            if (objImage3 != null)
            {
                this.ImageProductID3 = objImage3.ImageProductID;
                //bind image to UI
                this.ImageProduct3 = objImage3.FileName;
                BindImage(trImage3, trDelete3, imgProductImage3, lbtnDeleteImage3, this.ImageProduct3);
            }
            ImageProduct objImage4 = GetImageInList(lstImage, 3);
            if (objImage4 != null)
            {
                this.ImageProductID4 = objImage4.ImageProductID;
                //bind image to UI
                this.ImageProduct4 = objImage4.FileName;
                BindImage(trImage4, trDelete4, imgProductImage4, lbtnDeleteImage4, this.ImageProduct4);
            }

        }
    }
    private void BindImage(System.Web.UI.HtmlControls.HtmlTableRow trImage, System.Web.UI.HtmlControls.HtmlTableRow trDelete, System.Web.UI.WebControls.Image img, LinkButton lbtnDelete, string value)
    {
        string imagePage = "~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_THUMB_FOLDER + value;
        if (File.Exists(this.Page.Server.MapPath(imagePage)))
        {
            img.ImageUrl = imagePage;
            trImage.Visible = true;
            trDelete.Visible = true;
        }
        else
        {
            trImage.Visible = false;
            trDelete.Visible = false;
        }
    }
    private void InitData()
    {
        //  txtDescription.Mode = Common.Editor.TextEditor.TextEditorMode.Full;
        string validateGroup = "productDetail";
        vsumProduct.ValidationGroup = btnSave.ValidationGroup = cusProductImage1.ValidationGroup = reqProductName.ValidationGroup = reqSKU.ValidationGroup = validateGroup;
        cusProductImage1.ValidationGroup = cusNowPrice.ValidationGroup;
        //Init message
        reqProductName.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "Product name");
        reqSKU.ErrorMessage = string.Format(Resources.Resource.MSG_REQUIREMENT, "SKU");
        cusNowPrice.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Now Price");
        //cusWasPrice.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Was Price");
        cusProductImage1.ErrorMessage = string.Format(Resources.Resource.MSG_VALID, "Image");
        this.Command = clsQueryString.GetString("act");
        this.ProductID = clsQueryString.GetInt("id");
    }
    private void UpdateProduct(Product objProduct, ImageProductCollection lstImage)
    {
        busProduct objBus = new busProduct();
        objProduct.ProductID = this.ProductID;
        int result = objBus.Update(objProduct);
        if (result == 1)//successfull
        {
            busImageProduct objBusImage = new busImageProduct();
            //Re inser Product Category            
            ProductCategoryCollection lstCate = GetCategoryProduct();
            busProductCategory objBusCate = new busProductCategory();
            objBusCate.DeleteByProduct(this.ProductID);
            objBusCate.Insert(lstCate);
            //if has new upload image, re insert image, else hold old image
            lstImage[0].ProductID = lstImage[1].ProductID = lstImage[2].ProductID = lstImage[3].ProductID = this.ProductID;
            objBusImage.DeleteByProductID(this.ProductID);
            objBusImage.Insert(lstImage);
            Response.Redirect("ProductList.aspx?" + this.GetPageQuery);
        }
        else if (result == 0)//update error
            lblErrorMessage.Text = Resources.Resource.MSG_UPDATE_ERROR;
        else//SKU IS Exists
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "SKU");
    }
    private void InsertProduct(Product objProduct, ImageProductCollection lstImage)
    {
        busProduct objBus = new busProduct();
        int result = objBus.Insert(objProduct);
        if (result > 0)
        {
            this.ProductID = result;
            //Insert product category
            ProductCategoryCollection lstCate = GetCategoryProduct();
            busProductCategory objBusCate = new busProductCategory();
            objBusCate.Insert(lstCate);
            busImageProduct objBusImage = new busImageProduct();
            lstImage[0].ProductID = lstImage[1].ProductID = lstImage[2].ProductID = lstImage[3].ProductID = this.ProductID;
            objBusImage.Insert(lstImage);
            Response.Redirect("ProductList.aspx?" + this.GetPageQuery);
        }
        else if (result == 0)//insert error
        {
            //try delete  Image has Upload
            DeleteImage(lstImage[0].FileName);
            DeleteImage(lstImage[1].FileName);
            DeleteImage(lstImage[2].FileName);
            DeleteImage(lstImage[3].FileName);
            lblErrorMessage.Text = Resources.Resource.MSG_INSERT_ERROR;
        }
        else //SKU IS Exists
        {
            //try delete  Image has Upload
            DeleteImage(lstImage[0].FileName);
            DeleteImage(lstImage[1].FileName);
            DeleteImage(lstImage[2].FileName);
            DeleteImage(lstImage[3].FileName);
            lblErrorMessage.Text = string.Format(Resources.Resource.MSG_CHECK_EXISTS, "SKU");
        }
    }
    private ProductCategoryCollection GetCategoryProduct()
    {
        ProductCategoryCollection lstCate = new ProductCategoryCollection();
        string[] cate = hidCategoryIDSelect.Value.Split(';');
        if (cate.Length > 0)
        {
            int cateID;
            foreach (string s in cate)
            {
                cateID = clsConvert.Int(s);
                if (cateID > 0)
                {
                    ProductCategory objData = new ProductCategory();
                    objData.ProductID = this.ProductID;
                    objData.CategoryID = cateID;
                    lstCate.Add(objData);
                }
            }
        }      
        return lstCate;
    }
    private ImageProductCollection GetImageProduct()
    {
        ImageProductCollection lstResult = new ImageProductCollection();
        ImageProduct objImage1 = new ImageProduct();
        objImage1.FileName = UploadImage(fulProductImage1, this.ImageProduct1, txtSKU.Text);
        lstResult.Add(objImage1);
        ImageProduct objImage2 = new ImageProduct();
        objImage2.FileName = UploadImage(fulProductImage2, this.ImageProduct2, txtSKU.Text + "_1");
        lstResult.Add(objImage2);
        ImageProduct objImage3 = new ImageProduct();
        objImage3.FileName = UploadImage(fulProductImage3, this.ImageProduct3, txtSKU.Text + "_2");
        lstResult.Add(objImage3);
        ImageProduct objImage4 = new ImageProduct();
        objImage4.FileName = UploadImage(fulProductImage4, this.ImageProduct4, txtSKU.Text + "_3");
        lstResult.Add(objImage4);
        return lstResult;
        // return objImage;
    }
    private string UploadImage(FileUpload _ful, string _oldImage, string newFileName)
    {
        string newFullFileName = _oldImage;
        if (_ful.HasFile)
        {
            string fileNameUpload = _ful.FileName;
            string extFile = System.IO.Path.GetExtension(fileNameUpload).ToLower();
            newFullFileName = newFileName + extFile;

            string fullPath = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_FOLDER);//upload images           
            string pathResizeImages = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_IMAGES_FOLDER);
            string pathResizeThumb = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_THUMB_FOLDER);
            string pathResizeLarge = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_LARGE_FOLDER);
            string pathResizeSmall = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_SMALL_FOLDER);
            if (!string.IsNullOrEmpty(_oldImage))
            {
                this.DeleteImage(_oldImage);
            }
            _ful.SaveAs(fullPath + newFullFileName);

            System.Drawing.Imaging.ImageFormat imgFormat = clsImage.GetImageFormat(extFile);
            using (System.Drawing.Image imgPhoto = System.Drawing.Image.FromFile(fullPath + newFullFileName))
            {
                System.Drawing.Image imgSmall = clsImage.ScaleCrop(imgPhoto, 58, 58, AnchorPosition.Center, true, false);
                imgSmall.Save(pathResizeSmall + newFullFileName, imgFormat);
                imgSmall.Dispose();

                System.Drawing.Image imgThumb = clsImage.ScaleCrop(imgPhoto, 142, 142, AnchorPosition.Center, true, false);
                imgThumb.Save(pathResizeThumb + newFullFileName, imgFormat);
                imgThumb.Dispose();

                System.Drawing.Image imgResize = clsImage.ScaleCrop(imgPhoto, 197, 197, AnchorPosition.Center, true, false);
                imgResize.Save(pathResizeImages + newFullFileName, imgFormat);
                imgResize.Dispose();

                System.Drawing.Image imgLarge = clsImage.ScaleCrop(imgPhoto, 490, 490, AnchorPosition.Center, true, false);
                imgLarge.Save(pathResizeLarge + newFullFileName, imgFormat);
                imgLarge.Dispose();
            }  

            // delete source image
            clsFile.DeleteFile(fullPath + newFullFileName);
        }

        return newFullFileName;
    }
    private void DeleteImage(string _orgImageFileName)
    {
        string path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_IMAGES_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_THUMB_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);
        path = Server.MapPath("~/" + clsConfigData.DEFAULT_UPLOAD_PRODUCT_LARGE_FOLDER);
        clsFile.DeleteFile(path + _orgImageFileName);

    }
    private void DeleteImageInDB(int imageID, string imageName)
    {
        //delete image DB
        busImageProduct objBus = new busImageProduct();
        if (objBus.Delete(imageID))
        {
            //delete image in folder
            DeleteImage(imageName);
            Response.Redirect("ProductDetail.aspx?" + this.GetPageQuery);
        }
    }
    private void LoadDataCategory()
    {
        bool isExpand = true;
        //Get VideoCategory
        hidCategoryIDSelect.Value = string.Empty;
        //Load all Catgeory in Level 1
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        objCondition.Condition = " ParentId is null and Type=" + (byte)enmCategoryType.Product;
        busCategory objBus = new busCategory();
        CategoryCollection lstLevel1 = objBus.List(objCondition);//only return one object
        if (lstLevel1 != null && lstLevel1.Count > 0)
        {
            html = @"<table cellspacing='0' cellpadding='0' border='0'>
                        <tr>
                            <td style='padding:0px;'>
                                  <img height='22' width='16' src='../App_Themes/Admin/images/icons/folderplus2.gif' id='FFLD" + lstLevel1[0].CategoryID + @"'>
                            </td>
                            <td style='padding:0px;'>
                                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                            </td>
                           
                            <td nowrap='' style='padding:0px;'><input type='checkbox' " + GetSelectCheckBoxCategory(lstLevel1[0].CategoryID) + @" id='chkCategory_" + lstLevel1[0].CategoryID + @"'  onclick=CheckCategoryItem(" + lstLevel1[0].CategoryID + @",this.checked); />
                                    <a href='javascript:void(0);' onClick=SelectCateName(" + lstLevel1[0].CategoryID + @")>" + lstLevel1[0].Name + @"</a>
                            </td>
                            </tr>
                       </table>";
            CategoryCollection lstChild = GetChild(lstLevel1[0]);
            for (int i = 0; i < lstChild.Count; i++)
            {
                Category objBreadCrum = lstChild[i];
                if (i == lstChild.Count - 1)
                    html += BuildHTML(objBreadCrum, true, isExpand);
                else html += BuildHTML(objBreadCrum, false, isExpand);
            }
        }
    }
    private string GetSelectCheckBoxCategory(int cateId)
    {
        foreach (ProductCategory objCate in lstCate)
        {
            if (objCate.CategoryID == cateId)
            {
                lstCate.Remove(objCate);
                hidCategoryIDSelect.Value += cateId + ";";
                return "checked='checked'";
            }
        }
        return string.Empty;
    }
    private CategoryCollection GetChild(Category objData)
    {
        Category objCondition = new Category();
        objCondition.OrderBy = busCategory.SORTORDER;
        objCondition.OrderDirection = "ASC";
        objCondition.Condition = " ParentId=" + objData.CategoryID;
        objCondition.CurrentPage = 1;
        objCondition.PageSize = int.MaxValue;
        busCategory objBus = new busCategory();
        CategoryCollection lstResult = objBus.List(objCondition);
        return lstResult;
    }
    private string BuildHTML(Category objData, bool lastNode, bool isExpand)
    {
        string tdPadding = string.Empty;
        string result = string.Empty;
        for (int i = 2; i < objData.Level; i++)
        {
            tdPadding += @" <td style='padding:0px;'>
                    <img height='22' width='19' src='../App_Themes/Admin/images/icons/i2.gif'>
                </td>";
        }

        //get list child for this object
        CategoryCollection lstChild = GetChild(objData);
        if (lstChild != null && lstChild.Count > 0)
        {
            string folderexpand = string.Empty;
            string expandImage = string.Empty;
            if (objData.Level > 1 && lastNode)
            {
                expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/lplus2.gif'>";
            }
            else
            {
                if (isExpand)
                {
                    folderexpand = "folderminus2.gif";
                    expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/tminus2.gif'>";
                }
                else
                {
                    folderexpand = "folderplus2.gif";
                    expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/tplus2.gif'>";
                }
            }
            // expandImage = "  <img height='22' width='19' id='IMG" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/lplus2.gif'>";
            result += @"<table cellspacing='0' cellpadding='0' border='0'>
            <tr>
                " + tdPadding + @"
                <td  onclick=expandit(" + objData.CategoryID + @") style='padding:0px;'>
                    " + expandImage + @"
                </td>
                <td style='padding:0px;'>
                    <img height='22' width='16' id='FLD" + objData.CategoryID + @"' src='../App_Themes/Admin/images/icons/" + folderexpand + @"'>
                </td>
                <td width='4' style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td nowrap='' style='padding:0px;'><input type='checkbox' id='chkCategory_" + objData.CategoryID + @"' " + GetSelectCheckBoxCategory(objData.CategoryID) + @"  onclick=CheckCategoryItem(" + objData.CategoryID + @",this.checked); />
                    <a href='javascript:void(0);' onClick=SelectCateName(" + objData.CategoryID + @")>" + objData.Name + @"</a>
                </td>
            </tr>
        </table>";
            if (isExpand)
                result += "<span id='SPAN" + objData.CategoryID + "' style='display:block;'>";
            else result += "<span id='SPAN" + objData.CategoryID + "' style='display: none;'>";
            for (int index = 0; index < lstChild.Count; index++)
            {
                Category objBreadCrum = lstChild[index];
                if (index == lstChild.Count - 1)
                    result += BuildHTML(objBreadCrum, true, isExpand);
                else result += BuildHTML(objBreadCrum, false, isExpand);
            }
            result += "</span>";
        }
        else
        {
            string expandImage = string.Empty;
            if (lastNode)
            {
                expandImage = "  <img height='22' width='19'  src='../App_Themes/Admin/images/icons/l2.gif'>";
            }
            else expandImage = "  <img height='22' width='19'  src='../App_Themes/Admin/images/icons/t2.gif'>";

            result = @"<table cellspacing='0' cellpadding='0' border='0'>
            <tr>
                " + tdPadding + @"
                <td style='padding:0px;'>
                   " + expandImage + @"
                </td>
                <td style='padding:0px;'>
                    <img height='22' width='16' src='../App_Themes/Admin/images/icons/folderplus2.gif'>
                </td>
                <td width='4' style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td style='padding:0px;'>
                    <img height='16' width='4' src='../App_Themes/Admin/images/icons/spacer.gif'>
                </td>
                <td nowrap='' style='padding:0px;'>
                    <input type='checkbox' id='chkCategory_" + objData.CategoryID + @"' " + GetSelectCheckBoxCategory(objData.CategoryID) + @"  onclick=CheckCategoryItem(" + objData.CategoryID + @",this.checked); />
                    <a href='javascript:void(0);' onClick=SelectCateName(" + objData.CategoryID + @")>" + objData.Name + @"</a>
                </td>
            </tr>
        </table>";
        }
        return result;
    }
    #endregion

    #region Events

    protected void btnSave_Click(object sender, EventArgs e)
    {
        if (Page.IsValid)
        {
            //get data image value
            ImageProductCollection lstImage = GetImageProduct();
            //get datavalue
            Product objProduct = new Product();
            objProduct.ZoneId = Convert.ToInt32(drpZone.SelectedValue);
            objProduct.Status = Convert.ToInt32(drpStatus.SelectedValue);
            if(drpNote.SelectedValue != "")
                objProduct.NoteId = Convert.ToInt32(drpNote.SelectedValue);

            objProduct.CreatedBy = this.userloginName;
            objProduct.CreatedDate = clsDateTime.Now;
            objProduct.ShortDescription = txtShortDescription.Text;
            objProduct.Description = txtDescription.Text.Replace("font-family: Tahoma;", "");
            objProduct.Description = objProduct.Description.Replace("font-size: x-small;", "");
            objProduct.PageTitle = txtPageTitle.Text;
            objProduct.MetaKeywords = txtMetaKeywords.Text;
            objProduct.MetaDescription = txtMetaDescription.Text;
            objProduct.Site = txtSite.Text;
            objProduct.SKU = txtSKU.Text;
            objProduct.Video = txtVideo.Text;
            objProduct.Status = Convert.ToInt16(drpStatus.SelectedValue);
            objProduct.WasPrice = txtWasPrice.Text.Length > 0 ? clsConvert.Float(txtWasPrice.Text) : 0;
            if (txtSize.Text.Trim().Length > 0)
            {
                objProduct.Size = txtSize.Text.Trim();
            }
            else if (drpSize.SelectedValue != "")
            {
                objProduct.Size = drpSize.SelectedValue;
            }
            else
            {
                objProduct.Size = string.Empty;
            }

            if (txtColor.Text.Trim().Length > 0)
            {
                objProduct.Color = txtColor.Text.Trim();
            }
            else if (drpColor.SelectedValue != "")
            {
                objProduct.Color = drpColor.SelectedValue;
            }
            else
            {
                objProduct.Color = string.Empty;
            }

            if (txtMaterial.Text.Trim().Length > 0)
            {
                objProduct.Material = txtMaterial.Text.Trim();
            }
            else if (drpMaterial.SelectedValue != "")
            {
                objProduct.Material = drpMaterial.SelectedValue;
            }
            else
            {
                objProduct.Material = string.Empty;
            }

            if (txtMadeIn.Text.Trim().Length > 0)
            {
                objProduct.MadeIn = txtMadeIn.Text.Trim();
            }
            else if (drpMadeIn.SelectedValue != "")
            {
                objProduct.MadeIn = drpMadeIn.SelectedValue;
            }
            else
            {
                objProduct.MadeIn = string.Empty;
            }

            if (chkIsActive.Checked)
                objProduct.IsActive = true;
            else
                objProduct.IsActive = false;
            if (chkIsNew.Checked)
                objProduct.IsNew = true;
            else
                objProduct.IsNew = false;
            objProduct.Name = txtProductName.Text;
            objProduct.NowPrice = txtNowPrice.Text.Length > 0 ? clsConvert.Float(txtNowPrice.Text) : 0;
            objProduct.UpdatedBy = this.userloginName;
            objProduct.UpdatedDate = clsDateTime.Now;
            if (this.Command == "edit")
                UpdateProduct(objProduct, lstImage);
            else
                InsertProduct(objProduct, lstImage);
        }
        else
        {
            vsumProduct.ShowMessageBox = false;
            vsumProduct.ShowSummary = true;
        }
    }
    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("ProductList.aspx?" + this.GetPageQuery);
    }
    protected void lbtnDeleteImage1_Click(object sender, EventArgs e)
    {
        DeleteImageInDB(this.ImageProductID1, this.ImageProduct1);
    }
    protected void lbtnDeleteImage2_Click(object sender, EventArgs e)
    {
        DeleteImageInDB(this.ImageProductID2, this.ImageProduct2);
    }
    protected void lbtnDeleteImage3_Click(object sender, EventArgs e)
    {
        DeleteImageInDB(this.ImageProductID3, this.ImageProduct3);
    }
    protected void lbtnDeleteImage4_Click(object sender, EventArgs e)
    {
        DeleteImageInDB(this.ImageProductID4, this.ImageProduct4);
    }
    #endregion

    #region Validate Data
    protected void CheckSImageValid(object source, ServerValidateEventArgs args)
    {

        args.IsValid = clsImage.IsValidImage();
    }
    protected void CheckSWasPriceValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsValidate.CheckFloatValid(args.Value);
    }
    protected void CheckSNowPriceValid(object source, ServerValidateEventArgs args)
    {
        args.IsValid = clsValidate.CheckFloatValid(args.Value);
    }


    #endregion

}